package com.kcs.fxmargin.action;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.kcs.common.utils.Constant;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.action.form.OutstandingReportActionForm;
import com.kcs.fxmargin.bo.OutstandingBO;
import com.kcs.fxmargin.service.DealsService;

public class OutstandingReportAction extends FXAction{

	private Logger log = Logger.getLogger(Constant.LOG_FX);
	private DealsService service = new DealsService();
	private String formatDate = "dd/MM/yyyy";

	@Override
	public ActionForward process(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		
		log.info("OutstandingReportAction : Start");
		
		try {

			OutstandingReportActionForm formBean = (OutstandingReportActionForm) form;
	

			if ("init".equals(formBean.getAction())) {
				formBean.resetExpect();
				formBean.setOutStandingBOList(new ArrayList<OutstandingBO>());
			} else if ("search".equals(formBean.getAction())) {
				
				OutstandingBO bo = new OutstandingBO();
				
				if(formBean.getStartDate() != null && !"".equals(formBean.getStartDate())) 
					bo.setStartDate(commonUtils.stringToDate(formBean.getStartDate(), formatDate));
				else bo.setStartDate(new Date());
				
				if(formBean.getEndDate() != null && !"".equals(formBean.getEndDate())) 
					bo.setEndDate(commonUtils.stringToDate(formBean.getEndDate(), formatDate));
				else bo.setEndDate(new Date());
				
				formBean.setOutStandingBOList(service.searchOutstanding(bo));
				formBean.setAction("init");
				request.setAttribute(Constant.SHOW_RESULT, Constant.SHOW_RESULT);
				
			} else if ("exportToPDF".equals(formBean.getAction())) {
				
				formBean.setAction("init");
				exportToPDF(formBean, request, response);
			} else if ("exportToExcel".equals(formBean.getAction())) {
				
				formBean.setAction("init");
				exportToExcel(formBean, request, response);
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return (mapping.findForward("error"));
		}
		
		log.info("OutstandingReportAction : End");
		
		return mapping.findForward("outStanding");
	}
	
	@SuppressWarnings("deprecation")
	public void exportToExcel(OutstandingReportActionForm formBean, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("OutstandingReportAction : exportToExcel : Start");
		
		ServletOutputStream out	= null;
		HSSFWorkbook workbook 	= null;
		HSSFSheet sheet 		= null;
		HSSFRow row 			= null;
		HSSFCell cell 			= null;
		OutstandingBO bo 		= null;
		HSSFCellStyle style 	= null;
		HSSFFont font 			= null;
		Integer index			= 0;
		List<OutstandingBO> outStandingBOList = formBean.getOutStandingBOList();
		
		if(outStandingBOList != null && outStandingBOList.size() > 0){
			workbook 	= new HSSFWorkbook();
			sheet 		= workbook.createSheet("Outstanding by Maturity Report");
			style 		= workbook.createCellStyle();
			font 		= workbook.createFont();
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
						
			row = sheet.createRow(index);
			style = workbook.createCellStyle();
			style.setWrapText(false);
			style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("FORWARD CONTRACT SYSTEM");
			cell.setCellStyle(style);
			
			index++;
			
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
			
			row = sheet.createRow(index);
			style = workbook.createCellStyle();
			style.setWrapText(false);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setFont(font);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("KRUNG THAI BANK PLC.");
			cell.setCellStyle(style);
			index++;
			
			row = sheet.createRow(index);
			style = workbook.createCellStyle();
			style.setWrapText(false);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setFont(font);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Outstanding by Maturity Date between " + formBean.getStartDate() + " and " + formBean.getEndDate());
			cell.setCellStyle(style);
			index++;
			
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 9));
			sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 9));
			index++;
			
			//-- Header cell style
			style = workbook.createCellStyle();
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setAlignment(HSSFCellStyle.VERTICAL_BOTTOM);
			style.setFont(font);
			style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style.setFillForegroundColor(new HSSFColor.AQUA().getIndex());
		
			row = sheet.createRow(index);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Expiry Date");
			cell.setCellStyle(style);
			cell = row.createCell(1, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Deal Id");
			cell.setCellStyle(style);
			cell = row.createCell(2, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Customer");
			cell.setCellStyle(style);
			cell = row.createCell(3, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Deal Date");
			cell.setCellStyle(style);
			cell = row.createCell(4, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Base Rate");
			cell.setCellStyle(style);
			cell = row.createCell(5, Cell.CELL_TYPE_STRING);
			cell.setCellValue("All in Rate");
			cell.setCellStyle(style);
			
			cell = row.createCell(6, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Buy");
			cell.setCellStyle(style);
			cell = row.createCell(8, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Sell");
			cell.setCellStyle(style);
			
			index++;
			
			row = sheet.createRow(index);
			cell = row.createCell(6, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Ccy");
			cell.setCellStyle(style);
			cell = row.createCell(7, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Amount");
			cell.setCellStyle(style);
			cell = row.createCell(8, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Ccy");
			cell.setCellStyle(style);
			cell = row.createCell(9, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Amount");
			cell.setCellStyle(style);
			
			sheet.addMergedRegion(new CellRangeAddress(4, 5, 0, 0));
			sheet.addMergedRegion(new CellRangeAddress(4, 5, 1, 1));
			sheet.addMergedRegion(new CellRangeAddress(4, 5, 2, 2));
			sheet.addMergedRegion(new CellRangeAddress(4, 5, 3, 3));
			sheet.addMergedRegion(new CellRangeAddress(4, 5, 4, 4));
			sheet.addMergedRegion(new CellRangeAddress(4, 5, 5, 5));

			sheet.addMergedRegion(new CellRangeAddress(4, 4, 6, 7));
			sheet.addMergedRegion(new CellRangeAddress(4, 4, 8, 9));			
			
			index++;
			
			String eqDate = "";
					
			for(int i = 0 ; i < outStandingBOList.size() ; i++){
				bo = outStandingBOList.get(i);
				
				row = sheet.createRow(i+index);
				
				if(!eqDate.equals(commonUtils.formatDate(bo.getExpiryDate(), commonUtils.ddmmyyyywithslash))) {
					eqDate = commonUtils.formatDate(bo.getExpiryDate(), commonUtils.ddmmyyyywithslash);
					
					font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setFont(font);
					style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
					
					cell = row.createCell(0, Cell.CELL_TYPE_STRING);
					cell.setCellValue("Expriy Date : " + eqDate);
					cell.setCellStyle(style);					
										
					sheet.addMergedRegion(new CellRangeAddress(i+index, i+index, 0, 9));
					index++;
					
					row = sheet.createRow(i+index);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(0, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.formatDate(bo.getExpiryDate(), commonUtils.ddmmyyyywithslash));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(1, Cell.CELL_TYPE_STRING);
					cell.setCellValue(bo.getDealId());
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
					cell = row.createCell(2, Cell.CELL_TYPE_STRING);
					cell.setCellValue(bo.getCustomer());
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(3, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.formatDate(bo.getDealDate(), commonUtils.ddmmyyyywithslash));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
					cell = row.createCell(4, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.parseToFormat(bo.getBaseRate() + ""));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
					cell = row.createCell(5, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.parseToFormat(bo.getAllInRate() + ""));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(6, Cell.CELL_TYPE_STRING);
					cell.setCellValue(bo.getCcyBuy());
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
					cell = row.createCell(7, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.parseToFormat(bo.getBuyAmount() + ""));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(8, Cell.CELL_TYPE_STRING);
					cell.setCellValue(bo.getCcySell());
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
					cell = row.createCell(9, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.parseToFormat(bo.getSellAmount() + ""));
					cell.setCellStyle(style);
					
				} else {
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(0, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.formatDate(bo.getExpiryDate(), commonUtils.ddmmyyyywithslash));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(1, Cell.CELL_TYPE_STRING);
					cell.setCellValue(bo.getDealId());
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
					cell = row.createCell(2, Cell.CELL_TYPE_STRING);
					cell.setCellValue(bo.getCustomer());
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(3, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.formatDate(bo.getDealDate(), commonUtils.ddmmyyyywithslash));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
					cell = row.createCell(4, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.parseToFormat(bo.getBaseRate() + ""));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
					cell = row.createCell(5, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.parseToFormat(bo.getAllInRate() + ""));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(6, Cell.CELL_TYPE_STRING);
					cell.setCellValue(bo.getCcyBuy());
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
					cell = row.createCell(7, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.parseToFormat(bo.getBuyAmount() + ""));
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
					cell = row.createCell(8, Cell.CELL_TYPE_STRING);
					cell.setCellValue(bo.getCcySell());
					cell.setCellStyle(style);
					
					style = workbook.createCellStyle();
					style.setWrapText(false);
					style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
					cell = row.createCell(9, Cell.CELL_TYPE_STRING);
					cell.setCellValue(commonUtils.parseToFormat(bo.getSellAmount() + ""));
					cell.setCellStyle(style);
					
				}
				
			}
			
			HSSFFooter footer= sheet.getFooter();
			footer.setLeft("Print By : " + formBean.getUserLoginName());
			footer.setRight(commonUtils.formatDate(new Date(), commonUtils.ddmmyyyyhhmmsswithslash));
			
			@SuppressWarnings("unchecked")
			java.util.Iterator<HSSFCell> it = row.cellIterator(); 
		    while(it.hasNext()){ 
			         HSSFCell cellTmp = it.next(); 
			         sheet.autoSizeColumn((short)cellTmp.getCellNum(),true); 
			 }
			
		    sheet.getPrintSetup().setLandscape(true);
		    sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
		    
			response.setHeader("Pragma", "no-cache");
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment; filename=" + Constant.EXCEL_OUT_STANDING_FILENAME);
			
			out = response.getOutputStream();
			workbook.write(out);
			//out.flush();
			out.close();
			request.setAttribute(Constant.SHOW_RESULT, Constant.SHOW_RESULT);
			
			log.debug("Export excel successfully.");			

			log.debug("OutstandingReportAction : exportToExcel : End");
		}else{
			throw new Exception("Cannot export Excel: Data error.");
		}
	}

	public void exportToPDF(OutstandingReportActionForm formBean, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		float[] columnWidth 		= new float[]{100f,100f,300f,100f,100f,100f,80f,150f,80f,150f};
		PdfPTable pdfTable 			= null;
		PdfPCell pdfCell 			= null;
		Document pdf 				= null;
		Paragraph paragraph 		= null;
		Font font 					= null;
		Font font_blod				= null;
		Font font_header			= null;
		BaseFont baseFont 			= null;
		String fontFile 			= null;
		ByteArrayOutputStream baos 	= null;
		OutputStream os	 			= null;
		Rectangle rect 				= null;
		boolean result 				= false;
		List<OutstandingBO> outStandingBOList = formBean.getOutStandingBOList();
		
		log.info("Begin : OutstandingReportAction : exportToPDF");
		
		try{
			//Get Font Path
			
			// for test			
			//fontFile = request.getServletContext().getRealPath("/WEB-INF/font/tahoma.ttf");
			
			// for deploy
			fontFile = "/app/fxm-jboss/jboss-as/server/fxm-jboss/log/font/ARIALUNI.TTF";
			
			log.info("fontFile : "+fontFile);
			
			//Create Pdf Document
			pdf = new Document();
			rect = PageSize.A4;
			rect = rect.rotate();
			pdf.setPageSize(rect);
			pdf.setMarginMirroring(true);
			pdf.setMargins(10, 10, 30, 30);
			baos = new ByteArrayOutputStream();
			PdfWriter.getInstance(pdf, baos);
			pdf.open();
			
			//Add meta data
			pdf.addTitle("Outstanding by Maturity   Report");
			pdf.addSubject("Outstanding by Maturity   Report");
			pdf.newPage();
			
			//Create Font
			font 		= new Font(baseFont, 7, Font.NORMAL);
			font_header = new Font(baseFont, 8, Font.NORMAL);
			font_blod	= new Font(baseFont, 7, Font.BOLD);
			
			//Add Header paragraph
			paragraph 		= new Paragraph();			
			PdfPTable table = new PdfPTable(3);
	        int widths[] 	= {100,100,100};
	        table.setWidths(widths);
	        table.setWidthPercentage(100);
	
	        PdfPCell c1 = new PdfPCell(new Phrase("FORWARD CONTRACT SYSTEM", font));
	        c1.setHorizontalAlignment(Element.ALIGN_LEFT);
	        c1.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        c1.setBorder(0);
	        table.addCell(c1);
	
	        c1 = new PdfPCell(new Phrase("KRUNG THAI BANK PCL.\n\nOutstanding by Maturity Date " + formBean.getStartDate() + " and " + formBean.getEndDate() +"\n\n", font_header));
	        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
	        c1.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        c1.setBorder(0);
	        table.addCell(c1);
	
	        c1 = new PdfPCell(new Phrase("" , font_blod));
	        c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
	        c1.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        c1.setBorder(0);
	        table.addCell(c1);
	        
	        paragraph.add(table);
	        pdf.add(paragraph);
			
			//Create Table
			pdfTable = new PdfPTable(columnWidth);
			pdfTable.setWidthPercentage(100);
			
			//Set Table Header Font
			baseFont = BaseFont.createFont(fontFile, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			font = new Font(baseFont,10,Font.BOLD);
			
			//Set Table Header			
			
			pdfCell = new PdfPCell(new Phrase("Expiry Date",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthBottom(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Deal Id",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthBottom(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Customer",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthBottom(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Deal Date",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthBottom(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Base Rate",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthBottom(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("All in Rate",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthBottom(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Buy",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthBottom(0);
			pdfCell.setBorderWidthLeft(0);
			pdfCell.setColspan(2);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Sell",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthBottom(0);
			pdfCell.setBorderWidthLeft(0);
			pdfCell.setColspan(2);
			pdfTable.addCell(pdfCell);
			
			
			pdfCell = new PdfPCell(new Phrase("",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthTop(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthTop(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthTop(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthTop(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthTop(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthTop(0);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Ccy",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Amount",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Ccy",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfCell = new PdfPCell(new Phrase("Amount",font_blod));
			pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
			pdfCell.setBorderWidth(1);
			pdfCell.setBorderWidthLeft(0);
			pdfTable.addCell(pdfCell);
			
			pdfTable.setHeaderRows(1);
			//Set Table Data Font
			baseFont = BaseFont.createFont(fontFile, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			font = new Font(baseFont,8,Font.NORMAL);
			
			String eqDate = "";
			
			if(outStandingBOList != null){
				for(OutstandingBO data : outStandingBOList){
					
					if(!eqDate.equals(commonUtils.formatDate(data.getExpiryDate(), commonUtils.ddmmyyyywithslash))){
						pdfCell = new PdfPCell(new Phrase("Expiry Date : " + commonUtils.formatDate(data.getExpiryDate(), commonUtils.ddmmyyyywithslash),font_blod));
						pdfCell.setHorizontalAlignment(Element.ALIGN_LEFT);
						pdfCell.setColspan(10);
						pdfCell.setBorder(0);
						pdfTable.addCell(pdfCell);
						
						eqDate = commonUtils.formatDate(data.getExpiryDate(), commonUtils.ddmmyyyywithslash);
					}
					
					pdfCell = new PdfPCell(new Phrase(commonUtils.formatDate(data.getExpiryDate(), commonUtils.ddmmyyyywithslash),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(toStringNotNull(data.getDealId()),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(toStringNotNull(data.getCustomer()),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_LEFT);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(commonUtils.formatDate(data.getDealDate(), commonUtils.ddmmyyyywithslash),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(commonUtils.decimalRateFormat(data.getBaseRate()),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(commonUtils.decimalRateFormat(data.getAllInRate()),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(toStringNotNull(data.getCcyBuy()),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(commonUtils.parseToFormat(data.getBuyAmount() + ""),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(toStringNotNull(data.getCcySell()),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
					pdfCell = new PdfPCell(new Phrase(commonUtils.parseToFormat(data.getSellAmount() + ""),font));
					pdfCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
					pdfCell.setBorder(0);
					pdfTable.addCell(pdfCell);
					
				}	
			}
			
			paragraph = new Paragraph();
			paragraph.add(pdfTable);
			
			pdf.add(paragraph);
			
			pdf.close();
			
			//Attatch file
			response.setHeader("Pragma", "no-cache");
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition", "attachment; filename=" + Constant.PDF_OUT_STANDING_FILENAME);
			
			os = response.getOutputStream();			
			baos.writeTo(os);
			
			// Create a reader
			PdfReader reader = new PdfReader(baos.toByteArray());
	        
			// Create a stamper
		    PdfStamper stamper= new PdfStamper(reader, os);

		    // Loop over the pages and add a header to each page
		    
		    int n = reader.getNumberOfPages();
		    for (int i = 1; i <= n; i++) {
		    	getHeaderTable(formBean.getUserLoginName() , font).writeSelectedRows(0, -1, 10, 20, stamper.getOverContent(i));
		    }
		        // Close the stamper
		    stamper.close();
		    reader.close();
			
			os.flush();
			os.close();
			
			result = true;
			
		}catch(Exception e){
			if(pdf != null){
				pdf.close();
			}
			throw e;
		}
		
		log.info("export result: " + result);
		log.info("End : OutstandingReportAction : exportToPDF");
	}
	
	/**
     * Create a header table with page X of Y
     * @param x the page number
     * @param y the total number of pages
     * @return a table that can be used as header
     */
    public static PdfPTable getHeaderTable(String user, Font font) {
    	PdfPTable table = new PdfPTable(2);
        table.setTotalWidth(827);
        table.setWidthPercentage(100);
           
        PdfPCell c1 = new PdfPCell(new Phrase("Print By : " + user, font));
        c1.setHorizontalAlignment(Element.ALIGN_LEFT);
        c1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        c1.setBorder(0);        
        table.addCell(c1);
           
        PdfPCell c2 = new PdfPCell(new Phrase(commonUtils.formatDate(new Date(), commonUtils.ddmmyyyyhhmmsswithslash), font));
        c2.setHorizontalAlignment(Element.ALIGN_RIGHT);
        c2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        c2.setBorder(0);
        table.addCell(c2);
        
        return table;
    }
	
	private String toStringNotNull(Object o)throws Exception{
		return (o==null)?"":o.toString();
	}
	
}
